package com.ndp.fb.rdb.db.impl;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.config.annotation.Service;
import com.ndp.fb.rdb.api.EcMaterielTagRdbService;
import com.ndp.fb.rdb.db.DaoTemplate;
import com.ndp.fb.rdb.db.impl.mapper.DefaultRowMapper;
import com.ndp.fb.rdb.model.EcMaterielTag;

import java.util.List;

/**
 * Created by jacky.cheng on 2016/5/31.
 */
@Service
public class EcMaterielTagRdbServiceImpl extends DaoTemplate implements EcMaterielTagRdbService {

    @Override
    public List<EcMaterielTag> findTagsByMaterielId(Long materialId) {
        String sql = "SELECT DISTINCT tag.* \n" +
                "FROM ec_materiel_tag tag, ec_materiel_tags tags\n" +
                "WHERE tag.id = tags.ec_materiel_tag_id\n" +
                "and tags.ec_template_materiel_id = ? ";
        return getJdbcTemplate().query(sql, new Object[]{materialId}, DefaultRowMapper.autoRowMapper(EcMaterielTag.class));
    }

    @Override
    public List<EcMaterielTag> findByTagNameLike(Long orgId, String q) {
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT * from ec_materiel_tag t WHERE t.is_delete = 0 and  t.org_id = ? ");
        if (StringUtils.isNotEmpty(q)) {
            sql.append(" and t.tag_name like '%").append(q).append("%'");
        }
        sql.append(" ORDER BY t.create_time desc  ");
        return getJdbcTemplate().query(sql.toString(), new Object[]{orgId}, DefaultRowMapper.autoRowMapper(EcMaterielTag.class));
    }

    @Override
    public EcMaterielTag findByOrgIdTagName(Long orgId, String tagName){
        String sql = "SELECT * FROM  ec_materiel_tag WHERE is_delete=0 AND org_id =? AND tag_name=?";
        return findOne(sql, new Object[]{orgId,tagName}, DefaultRowMapper.autoRowMapper(EcMaterielTag.class));
    }

    @Override
    public Long save(EcMaterielTag tag) {
        return saveResultId(tag);
    }

    @Override
    public void saveRelation(Long templateId, Long tagId) {
        String sql ="INSERT INTO `ec_materiel_tags` ( `ec_materiel_tag_id`, `ec_template_materiel_id`) " +
                "VALUES ( ?, ? );";

        getJdbcTemplate().update(sql, new Object[]{tagId, templateId});
    }
}
